var xhChart = function(){
    this._chart      = null;       //图表对象
    this._option     = {};
    this._title      = '';
    this._series     = [];
    this._data       = {};          //图表数据（需处理）
    this._color      = ['#59ADF3', '#AF89D6', '#FF999A', '#FFCC67', '#86D560'];
    this._total      = 0;          //总数据量
    this._xBaseCount = 10;          //数据显示基数（计算展示比例）

    /**
     * 初始化chart，处理回调并渲染
     *
     * @param _dom
     * @param _source
     * @param _config
     * @param _newOption
     * @param _callback
     *
     * create by ck 20170526
     */
    this.init = function(_dom, _source, _config, _newOption, _callback){
        var $this = this;

        //初始化echarts实例
        if(_dom.id && _dom.id.indexOf('ec_') >= 0){
            this._chart = _dom;
        }
        else if(_dom instanceof jQuery){
            _dom = _dom[0];
            this._chart = echarts.init(_dom);
        }
        else if(typeof _dom == 'string'){
            _dom = document.getElementById(_dom);
            this._chart = echarts.init(_dom);
        }
        this._chart.showLoading();

        //如果为string则转为object(转换字符串形式json)
        if(typeof _source == 'string') {
            _source = JSON.parse(_source);
        }
        //如果数据源定义了url，则根据url获取数据，否则直接显示
        if(_source.url){
            $.ajax({
                type: 'POST',
                url: _source.url,
                data: _source.params ? _source.params : {},
                async: true,
                dataType: 'json',
                complete: function(XMLHttpRequest){
                    var result = XMLHttpRequest.responseJSON || XMLHttpRequest.responseText;
                    afterAjax(result);
                }
            });
            // .done(function(data){
            //     afterAjax(data);
            // }).fail(function(e, msg){
            //     console.log(e.statusText);
            //     console.log(msg);
            // });
        }
        else{
            afterAjax(_source);
        }

        function afterAjax(_data){
            //处理配置
            $this._data = _data;
            if(_config)             $this._config     = _config;
            if(_config.title)       $this._title      = _config.title;
            if(_config.color)       $this._color      = _config.color;
            if(_config.xBaseCount)  $this._xBaseCount = _config.xBaseCount;
            if(_data.series)        $this._series     = _data.series;
            if(_config.series)      $this._series     = _config.series;

            //计算基数及总数，用于初始化展示时计算展示百分比
            var _total = 0;
            $.each(_data, function (key, value) {
                if(value.length > _total) {
                    _total = value.length;
                }
            });
            $this._total = _total;

            //回调
            if(_callback){
                _callback.call(this);
            }
            $this._option.color = $this._color;
            $this._option.title = {
                text: $this._title,
                left: '7%',
                textStyle: {
                    fontSize: 20
                }
            };

            //如果有额外配置，则合并，以额外配置为准
            if (_newOption) {
                $this._option = $.extend(true, $this._option, _newOption);
            }
            $this._chart.setOption($this._option);
            $this._chart.hideLoading();
            //return $this._chart;
        }
    };

    /**
     * 柱状图表的绘制
     *
     * @param _dom         --容器ID|dom对象|jquery对象
     * {
     *      "url":"数据来源",
     *      "params": {"变量名": "值"}
     * }
     * or
     * {
     *      "xList": ["名称1", "名称2", "名称3"],
     *      "yList": ["值1", "值2", "值3"]
     * }
     * @param _source       --数据源
     * {
     *      "title": "图表标题",
     *      "yTitle": "y轴标题",
     *      "xBaseCount": "x轴基量（单页面x轴显示数量）",
     *      "series": [
     *          {"name": "项名1", "source": "数据源键名1"},
     *          {"name": "项名2", "source": "数据源键名2"}
     *      ]
     * }
     * @param _config       --常用变量
     * @param _newOption    --自定义新的option
     * @constructor
     *
     * create by cd 20161219
     * modify by ck 20161228    提供多种数据来源方式，项名可以从数据源读取，默认参数更改，优化注释
     * modify by ck 20170103    可传ID或对象，方法返回ECharts对象（以便绑定事件，避免重复初始化）
     * modify by ck 20170104    去除对象，防止数据残留
     * modify by ck 20170506    封装，dom对象更改，支持jquery，string，dom对象
     */
    this.bar = function(_dom, _source, _config, _newOption){
        var $this = this;
        $this.init(_dom, _source, _config, _newOption, function(){
            var _legends = [], _series = [];
            $.each($this._series, function (index, series) {
                _series.push({
                    name: series.name,
                    type: 'bar',
                    data: $this._data[series.source],
                    label: {
                        normal: {
                            show: _config.showSeriesInfo == false ? _config.showSeriesInfo : true,
                            position: 'top',
                            textStyle: {
                                fontWeight: 'bolder',
                                fontSize: _config.seriesFontSize ? _config.seriesFontSize : 12
                            }
                        }
                    }
                });
                if(_config.showLegends != false) {
                    _legends.push(series.name);
                }
            });

            $this._option = {
                tooltip: {
                    trigger: 'axis'
                },
                toolbox: {
                    itemSize: 20,
                    show: _config.showTool == false ? _config.showTool : true,
                    right: '1%',
                    feature: {
                        mark: {show: true},
                        dataView: {show: true, readOnly: false},
                        magicType: {show: true, type: ['line', 'bar']},
                        restore: {show: true},
                        saveAsImage: {show: true}
                    }
                },
                calculable: true,
                legend: {
                    data: _legends,
                    itemGap: 10,
                    itemHeight: 20,
                    itemWidth: 20
                },
                grid: {
                    top: '15%',
                    left: '3%',
                    right: '5%',
                    bottom: '15%',
                    containLabel: true
                },
                xAxis: [{
                    //设置字体倾斜
                    axisLabel: {
                        interval: 0,
                        rotate: 15,//倾斜度 -90 至 90 默认为0
                        margin: 20,
                        textStyle: {
                            fontWeight: "bolder",
                            color: "#000000",
                            fontSize: _config.xFontSize ? _config.xFontSize : 14
                        }
                    },
                    type: 'category',
                    axisTick: {
                        alignWithLabel: true
                    },
                    data: $this._data.xList
                }],
                yAxis: [{
                    type: 'value',
                    splitArea: {show: true},
                    name: _config.yTitle ? _config.yTitle : '总量',
                    min: 0,
                    position: 'left',
                    axisLabel: {
                        formatter: '{value}',
                        textStyle: {
                            fontSize: _config.yFontSize ? _config.yFontSize : 12
                        }
                    }
                }],
                dataZoom: [
                    {
                        show: _config.showZoom != undefined ? _config.showZoom : true,
                        start: 0,//数据窗口范围的起始百分比
                        end: ($this._xBaseCount / $this._total) * 100
                    }
                ],
                series: _series
            };
        });
        return $this._chart;
    };

    /**
     * 线状图表的绘制
     *
     * @param _dom         --容器ID|dom对象|jquery对象
     * {
     *      "url":"数据来源",
     *      "params": {"变量名": "值"}
     * }
     * or
     * {
     *      "xList": ["名称1", "名称2", "名称3"],
     *      "yList": ["值1", "值2", "值3"]
     * }
     * @param _source       --数据源
     * {
     *      "title": "图表标题",
     *      "yTitle": "y轴标题",
     *      "xBaseCount": "x轴基量（单页面x轴显示数量）",
     *      "series": [
     *          {"name": "项名1", "source": "数据源键名1"},
     *          {"name": "项名2", "source": "数据源键名2"}
     *      ]
     * }
     * @param _config       --常用变量
     * @param _newOption    --自定义新的option
     * @constructor
     *
     * create by cd 20161219
     * modify by ck 20170506    封装，同柱状图
     */
    this.line = function(_dom, _source, _config, _newOption) {
        var $this = this;
        $this.init(_dom, _source, _config, _newOption, function(){
            var _legends = [], _series = [];
            $.each($this._series, function (index, series) {
                _series.push({
                    name: series.name,
                    type: 'line',
                    data: $this._data[series.source],
                    label: {
                        normal: {
                            show: _config.showSeriesInfo == false ? _config.showSeriesInfo : true,
                            position: 'top',
                            textStyle: {
                                fontWeight: 'bolder',
                                fontSize: _config.seriesFontSize ? _config.seriesFontSize : 12
                            }
                        }
                    }
                });
                if(_config.showLegends != false) {
                    _legends.push(series.name);
                }
            });

            $this._option = {
                tooltip: {
                    trigger: 'axis'
                },
                toolbox: {
                    itemSize: 20,
                    show: _config.showTool == false ? _config.showTool : true,
                    right: '1%',
                    feature: {
                        mark: {show: true},
                        dataView: {show: true, readOnly: false},
                        magicType: {show: true, type: ['line', 'bar']},
                        restore: {show: true},
                        saveAsImage: {show: true}
                    }
                },
                calculable: true,
                legend: {
                    data: _legends,
                    itemGap: 10,
                    itemHeight: 20,
                    itemWidth: 20
                },
                grid: {
                    top: '15%',
                    left: '3%',
                    right: '3%',
                    bottom: '15%',
                    containLabel: true
                },
                xAxis: [{
                    //设置字体倾斜
                    axisLabel: {
                        interval: 0,
                        rotate: 15,//倾斜度 -90 至 90 默认为0
                        margin: 20,
                        textStyle: {
                            fontWeight: "bolder",
                            color: "#000000",
                            fontSize: _config.xFontSize ? _config.xFontSize : 14
                        }
                    },
                    type: 'category',
                    axisTick: {
                        alignWithLabel: true
                    },
                    data: $this._data.xList
                }],
                yAxis: [{
                    type: 'value',
                    splitArea: {show: true},
                    name: _config.yTitle ? _config.yTitle : '总量',
                    min: 0,
                    position: 'left',
                    axisLabel: {
                        formatter: '{value}',
                        textStyle: {
                            fontSize: _config.yFontSize ? _config.yFontSize : 12
                        }
                    }
                }],
                dataZoom: [
                    {
                        show: _config.showZoom != undefined ? _config.showZoom : true,
                        start: 0,//数据窗口范围的起始百分比
                        end: ($this._xBaseCount / $this._total) * 100
                    }
                ],
                series: _series
            }
        });
        return $this._chart;
    };
    /**
     * 饼图的绘制
     *
     * @param _dom         --容器ID|dom对象|jquery对象
     * {
     *      "url":"数据来源",
     *      "params": {"变量名": "值"}
     * }
     * or
     * [
     *      {"name":"项目1","value":"数量1"},
     *      {"name":"项目2","value":"数量2"}
     * ]
     * @param _source       --数据源
     * {
     *      "title": "图表标题"
     * }
     * @param _config       --常用变量
     * @param _newOption    --自定义新的option
     * @constructor
     *
     * create by cd 20161219
     * modify by ck 20170103    提供多种数据来源方式，项名可以从数据源读取，默认参数更改，优化注释
     * modify by ck 20170104    去除对象，防止数据残留
     * modify by ck 20170506    封装，dom对象更改，支持jquery，string，dom对象
     * modify by ck 20170525    封装环形图，根据数量自动判断显示
     */
    this.pie = function(_dom, _source, _config, _newOption) {
        var $this = this;
        $this.init(_dom, _source, _config, _newOption, function(){
            var _series             = [],
                _seriesRadiusStart  = 0,
                _seriesCount        = $this._series.length,
                _seriesRadiusStep   = 95 / _seriesCount - 1;

            $.each($this._series, function (index, series) {
                _series.push({
                    name: series.name,
                    type: 'pie',
                    data: $this._data[series.source],
                    radius: [_seriesRadiusStart + '%', _seriesRadiusStart + _seriesRadiusStep + '%'],
                    label: {
                        normal: {
                            show: _config.showSeriesInfo == false ? _config.showSeriesInfo : true,
                            position: (index + 1) == _seriesCount ? 'outside' : 'inner'
                        }
                    }
                });
                _seriesRadiusStart += (_seriesRadiusStep + 1);
            });

            $this._option = {
                tooltip: {
                    trigger: 'item',
                    formatter: _seriesCount == 1 ? "{b}: {c} ({d}%)" : "{a} <br/>{b}: {c} ({d}%)"
                },
                textStyle: {
                    fontSize: 14
                },
                series: _series
            };
        });
        return $this._chart;
    }
};